package com.lfnyxy.web;

import com.lfnyxy.common.dto.ApiResult;
import com.lfnyxy.common.dto.CodeMessage;
import com.lfnyxy.query.CaptchaQuery;
import com.lfnyxy.util.VerifyCodeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author daoqiang shen <daoqiang.shen@runtutech.com> on 2016/1/8.
 */
@Controller
public class CaptchaController {

	@RequestMapping(value = "captcha/get", method = RequestMethod.GET)
	public void doPost(HttpSession session, HttpServletResponse resp) throws IOException {
		resp.setHeader("Pragma", "No-cache");  
		resp.setHeader("Cache-Control", "no-cache");  
		resp.setDateHeader("Expires", 0);  
		resp.setContentType("image/jpeg");  
	          
	        //生成随机字串  
	        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
	        //存入会话session    
	        session.setAttribute("CAPTCHA", verifyCode.toLowerCase());  
	        //used for debug
	        System.err.println(verifyCode.toLowerCase());
	        
	        //生成图片  
	        int w = 140, h = 60;  
	        VerifyCodeUtils.outputImage(w, h, resp.getOutputStream(), verifyCode);
	}

	@RequestMapping(value = { "captcha/validate" }, method = { RequestMethod.POST })
	@ResponseBody
	public ApiResult<Object> validateCaptcha(
            @RequestBody CaptchaQuery query, HttpSession session) {
		String genCode = (String) session.getAttribute("CAPTCHA");
		if (StringUtils.isEmpty(genCode)) {
			return ApiResult.error(CodeMessage.LOGIN_CODE_EXPIRE);
		} else {
			if (!genCode.equalsIgnoreCase(query.getCode())) {
				return ApiResult.error(CodeMessage.LOGIN_CODE_ERROR);
			}
			return ApiResult.success((Object)"验证通过");
		}
	}

}
